<template>
  <div class="header_box">
    <div>活动名称：{{ topData.activity_name }}</div>
    <div>创建人：{{ topData.created_uid_name }}</div>
    <div>创建时间：{{ topData.created_at }}</div>
    <div v-if="topData.period_type == 1">创建有效期：永久</div>
    <div v-else>有效期：{{ topData.begin_date }} 至 {{ topData.end_date }}</div>
    <div
      >状态：
      <span v-if="topData.status == '未开始'" style="color: #969696"> {{ topData.status }} </span>
      <span v-if="topData.status == '进行中'" style="color: #59d2a0"> {{ topData.status }} </span>
      <span v-if="topData.status == '已结束'" style="color: #ff6b00"> {{ topData.status }} </span>
      <span v-if="topData.status == '提前结束'" style="color: #fe292b"> {{ topData.status }} </span>
    </div>
    <div>提前结束时间：{{ topData.real_end_date ? topData.real_end_date : '暂无' }}</div>
  </div>
  <!-- <div class="search_box">
  </div> -->
  <ZwSearchForm row-num="3" :option="searchOption2" @search="search" @reset="reset" @expand="getTableH" />
  <div class="table_box">
    <div class="export_box">
      <div>参与客户列表</div>
      <el-button @click="onExport(searchOption)">导出</el-button>
    </div>
    <ZwTable ref="tableRef" class="table-box" :option="tableOption" :rowKey="getRowKey" :fetch-params="state.searchParams" :fetch-api="fetchApi()"></ZwTable>
  </div>
  <OnHelp ref="OnHelpRef" :onHelpList="onHelpList" :custId="custId"></OnHelp>

  <!-- 删除弹框 -->
  <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
</template>

<script setup lang="tsx">
  import { ref, computed, reactive } from 'vue'
  import { Picture as IconPicture } from '@element-plus/icons-vue'
  import { useRoute, useRouter } from 'vue-router'
  import { deepCopy } from '@/utils/helper'
  import ZwSearchForm from '@/components/zw/search-form/SearchForm'

  import ZWTableSearch from './components/ZWTableSearch.vue'
  import ZWPagination from '@/components/ZWPagination.vue'
  import OnHelp from './components/OnHelp.vue'
  import ZWDeletdialog from '@/components/ZWDeletdialog.vue'
  import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus'
  import { partakeBaseinfo, partakeList, partakeRecord, fissionDispense, fissionExport } from '@/api/smartMarketing/envelopesFission'
  import { useStore } from '@/store'
  import ZwTable from '@/components/zw/table/Table'

  const store = useStore()
  const route = useRoute()
  const DeletdialogRef: any = ref(null)
  const router = useRouter()
  const OnHelpRef = ref(null)
  const tableRef:any = ref(null)
  const searchOption = [
    {
      label: '发放状态',
      key: 'dispense_status',
      value: -1,
      type: 'select',
      option: [
        { value: -1, label: '全部' },
        { value: 1, label: '已发放' },
        { value: 2, label: '未发放' }
      ]
    },
    {
      label: '任务状态',
      key: 'mission_status',
      value: -1,
      type: 'select',
      option: [
        { value: -1, label: '全部' },
        { value: 1, label: '完成' },
        { value: 2, label: '未完成' }
      ]
    },
    { label: '客户姓名', key: 'name', value: '', type: 'input' }
  ] 
  const getRowKey = (row: any) => {
    return row.id
  }
  const searchOption2 = computed(() => {
    return [
      
      {
        label: '发放状态',
        name: 'dispense_status',
        value: '',
        type: 'select',
        placeholder: '请选择',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
              resolve([
                { name: '全部', id: -1 },
                { name: '已发放', id: 1 },
                { name: '未发放', id: 2 }
              ])
          })
        },
        formatOption: (v: { name: any; id: any }) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '任务状态',
        name: 'mission_status',
        value: '',
        type: 'select',
        placeholder: '请选择',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
              resolve([
                { name: '全部', id: -1 },
                { name: '完成', id: 1 },
                { name: '未完成', id: 2 }
              ])
          })
        },
        formatOption: (v: { name: any; id: any }) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '客户姓名',
        name: 'name',
        value: '',
        type: 'input',
        width: '280px',
        placeholder: '请输入'
      },
    ]
  })
  const tableOption = [
    {
      prop: 'title',
      label: '参与人',
      render({ row, column, index }) {
        const slotError = () => (
          <div class="image_slot">
            <ElIcon>
              <IconPicture />
            </ElIcon>
          </div>
        )
        return (
          <div class="cusInfo">
            <ElImage preview-src-list={[row.headimgurl]} vSlots={{ error: slotError }} preview-teleported={true} src={row.headimgurl} fit="cover" class="avatar"></ElImage>
            <span style="margin-left: 6px">
              { row.nickname }<span vShow={row.remark}>（{ row.remark }）</span></span
            >
          </div>
        )
      }
    },
    {
      label: '任务状态',
      prop: 'mission_status',
      render({row}) {
        return (
          <span>{row.mission_status || '--'}</span>
        )
      }
    },
    {
      label: '已拆金额/总金额',
      prop: 'employee_name',
      render({row}) {
        return(
          <span>{row.amount}/{row.red_envelope_money}</span>
        )
      }
    },
    {
      label: '助力人数',
      prop: 'total_help_num',
      render({row}) {
        return (
          <span>{row.total_help_num }</span>
        )
      }
    },
    {
      label: '参与时间',
      prop: 'created_at',
      render({row}) {
        return (
          <span>{row.created_at || '--'}</span>
        )
      }
    },
    {
      label: '发放状态',
      prop: 'dispense_status',
      render({row}) {
        return (
          <span>{row.dispense_status || '--'}</span>
        )
      }
    },
    {
      prop: 'operate',
      label: '操作',
      align: 'left',
      fixed: 'right',
      width: 300,
      isOperate: true,
      renderOperate({row}) {
        return (
          <>
            <ElButton size="small" onClick={() => onGrant(row)} vShow={row.status == 1 && row.award_status == 2}>发放</ElButton> 
            <ElButton size="small" onClick={() => onHelp(row)}>助力记录</ElButton> 
            <ElButton size="small" onClick={() => router.push(`/customer/manage/list/detail?id=${row.cust_id}`)}>客户详情</ElButton> 
          </>
        )
      }
    }
  ]
  const defaultParams = reactive({
    activity_id: route.query.id,
    name: '',
    dispense_status: -1,
    mission_status: -1,
  })
  const state = reactive({
    searchParams: deepCopy({...defaultParams, activity_id: route.query.id})
  })
  const fetchApi = () => {
    // 获取文件列表
    // getTableH()
    return partakeList
  }
  const search = async (data: any) =>{
    const params = {
      activity_id: route.query.id,
      name: data?.name || '',
      dispense_status: data?.dispense_status || -1, // 发放状态 -1全部 1-已发放 2-未发放
      mission_status: data?.mission_status || -1, //任务状态 -1全部 1-未完成 2-已完
    }
    state.searchParams = deepCopy(params)
  }
  const reset = async (v:any):Promise<void> => {
    state.searchParams = deepCopy(defaultParams)
  }
  const topData = ref([])
  const activity_id = ref('')
  partakeBaseinfo({ activity_id: route.query.id }).then((res: any) => {
    topData.value = res
    console.log(topData)
  })

  const AllData = ref([])
  const effectTime = ref(['', ''])
  const dispense_status = ref('')
  const mission_status = ref('')

  const custId = ref('')
  const onHelpList = ref('')
  // const helpData = ref([])
  const onHelp = async (item: any) => {
    onHelpList.value = item
    custId.value = item.cust_id
    OnHelpRef.value.state.searchParams.cust_id = item.cust_id
    OnHelpRef.value.showDrawer = true
  }
  let cust_id = ref('')
  const onGrant = async (v) => {
    cust_id.value = v.cust_id
    DeletdialogRef.value.appDialog.visible = true
    DeletdialogRef.value.appDialog.title = '发放'
    DeletdialogRef.value.content = '确定发放当前红包吗吗？'
  }
  const onSubmit = async () => {
    const res = await fissionDispense({ activity_id: route.query.id, cust_id: cust_id.value })
    if (res.is_lack_balance == 1) {
      ElMessage.error('发放失败，账号余额不足，请先充值')
    } else {
      ElMessage.success('发放成功')
      tableRef.value.reload()
    }
    DeletdialogRef.value.appDialog.visible = false
  }
  const onExport = async (data?: any) => {
    let params = {
      activity_id: route.query.id,
      name: '',
      dispense_status: dispense_status.value || -1, // 发放状态 -1全部 1-已发放 2-未发放
      mission_status: mission_status.value || -1 //任务状态 -1全部 1-未完成 2-已完成
    }
    const res = await fissionExport(params)
    window.open(res.url)
    ElMessage.success('导出成功')
  }
</script>

<style lang="scss" scoped>
  .header_box {
    display: flex;
    justify-content: space-between;
    padding: 20px 26px;
    background: #ffffff;
    box-shadow: 0px 4px 4px 0px rgba(240, 240, 240, 0.5);
    border: 1px solid #eaeaea;
    font-size: 14px;
    color: #33302d;
  }

  .search_box {
    margin: 16px 0;
    padding: 20px 10px;
    background: #ffffff;
    border: 1px solid #eaeaea;
    font-size: 14px;
    color: #33302d;
    .zw-table-search {
      // margin-bottom: 16px;
      background-color: #fff;
    }
  }
  .table_box {
    padding: 20px;
    background-color: #fff;
    .export_box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      background: #ffffff;
      font-size: 14px;
      color: #33302d;
      .zw-table-search {
        // margin-bottom: 16px;
        background-color: #fff;
      }
    }
  }
  :deep(.avatar) {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    font-size: 36px;
  }
  :deep(.cusInfo) {
    display: flex;
    align-items: center;
  }
</style>
